package com.mark.springboot.config;

import com.mark.springboot.component.LoginHandlerInterceptor;
import com.mark.springboot.component.MyLocalResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 使用WebMvcConfigurer 可以扩展SpringMVC的功能
 *
 * @author MARKCC
 * @date 2018/10/11-11:13
 * @email markerccc@163.com
 */
@Configuration
// @EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		// 添加视图解析器, 当访问/mark的时候, 跳转到success页面
		// 效果就是: 浏览器发送/mark 请求,也来到success页面, 只要没放数据,就没必要写类似于hello那种控方法
		registry.addViewController("/mark").setViewName("/success");
	}

	/**
	 * 所有的WebMVCConfigurerAdapter组件都会一起起作用
	 *
	 * @return WebMvcConfigurer
	 * @Bean 将组件注册在容器中
	 */
	@Bean
	public WebMvcConfigurer webMvcConfigurer() {

		return new WebMvcConfigurer() {
			@Override
			public void addViewControllers(ViewControllerRegistry registry) {
				registry.addViewController("/").setViewName("login");
				registry.addViewController("/index.html").setViewName("login");
				registry.addViewController("/main.html").setViewName("dashboard");
			}

			/**
			 * 注册拦截器
			 * 
			 * @param registry
			 */
			@Override
			public void addInterceptors(InterceptorRegistry registry) {
				// 拦截任意请求, super.addInterceptors(registry);
				// 静态资源: *.css, *.js
				// SpringBoot已经做好了静态资源映射, 可以不用处理静态资源
				registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
						.excludePathPatterns("/index.html", "/", "/user/login");
			}
		};
	}

	/**
	 * 将国际化组件添加到容器中
	 *
	 * @return LocaleResolver
	 */
	@Bean
	public LocaleResolver localeResolver() {
		return new MyLocalResolver();
	}

}
